import uuid
import json
import models
from flask import g
from flask import jsonify
from apis import api_routes
from public.config import config
from typing import List
from typing import Union
from sqlalchemy import and_
from models.users.roles import Roles
from models.users.users import Users
from models.extra.extra import Charge
from public.local import datetime_type
from models.facility.facility import Facility as Ft
from models.product.craft import CraftInit
from models.product.routes import Routes
from models.product.aircraft import Aircraft
from models.product.craft import Craft


@api_routes.route("/system", methods=["POST"])
def func_system_database_post_api():
    """
    且在开发者模式下才能使用， 系统数据库表初始化，后端操作
    http://127.0.0.1:8080/api/system
    Content-Type=application/json
    methods=["POST"]
    :return:
        {'status': 400, 'msg': "不是开发者模式禁止建立数据库"}
        {"status": 200, 'message': 'system 数据库表已创建'}
    ---
    tags:
      - 后端开发者使用->ERROR
    """

    if config.DEVELOP is not True:
        return jsonify({'status': 400, 'msg': "不是开发者模式禁止建立数据库"})

    models.BaseModels.metadata.create_all(models.engine)
    return jsonify({"status": 200, 'message': 'system 数据库表已创建'}), 200


@api_routes.route("/system/init", methods=["POST"])
def func_system_database_init_post_api():
    """
    且在开发者模式下才能使用，系统数据初始化工作，后端操作
    http://127.0.0.1:8080/api/system/init
    Content-Type=application/json
    methods=["POST"]
    :return:
        {'status': 400, 'msg': "不是开发者模式禁止初始化数据库"}
        {'status': 200, 'msg': "开发者模式系统数据初始化成功"}
    ---
    tags:
      - 后端开发者使用->ERROR
    """
    if not config.DEVELOP:
        return jsonify({'status': 400, 'msg': "不是开发者模式禁止删除数据库"})

    roles: list = ["admin"]
    describes: list = ["超级管理员"]
    for index, itr in enumerate(roles):
        role: Union[Roles, None] = g.session.query(Roles).filter(Roles.role == itr).first()
        if role is None:
            g.session.add(Roles(role=itr, describe=describes[index]))
    g.session.commit()

    user: Union[Users, None] = g.session.query(Users).filter(Users.account == "admin").first()
    if user is None:
        role: Roles = g.session.query(Roles).filter(Roles.role == "admin").first()
        g.session.add(Users(
            account="admin", name="admin", phone=None, framework="管理员组",
            password="123456", role_id=role.id, time=datetime_type(), enable=True, modify=datetime_type()
        ))
    g.session.commit()
    user: Union[Users, None] = g.session.query(Users).filter(Users.account == "admin").first()
    charge: Union[Charge, None] = g.session.query(Charge).first()
    if charge is None:
        g.session.add(Charge(
            user_id1=user.id,
            user_id2=user.id,
            user_id3=user.id
        ))
    g.session.commit()

    return jsonify({'status': 200, 'msg': "开发者模式系统数据初始化成功"})


@api_routes.route("/system", methods=["DELETE"])
def func_system_database_delete_api():
    """
    系统表全部删除， 且在开发者模式下才能使用，且需要系统及权限才能操作, 后端操作
    http://127.0.0.1:8080/api/system
    Content-Type=application/json
    methods=["DELETE"]
    :return:
        {'status': 400, 'msg': "不是开发者模式禁止删除数据库"}
        {'status': 200, 'msg': "开发者模式系统数据表删除成功"}
    ---
    tags:
      - 后端开发者使用->ERROR
    """
    if not config.DEVELOP:
        return jsonify({'status': 400, 'msg': "不是开发者模式禁止删除数据库"})
    models.BaseModels.metadata.drop_all(models.engine)
    return jsonify({'status': 200, 'msg': "开发者模式系统数据表删除成功"})


@api_routes.route("/system", methods=["GET"])
def func_system_database_get_api():
    """
    导出数据备份，且在开发者模式下才能使用，且需要系统及权限才能操作, 后端操作
    http://127.0.0.1:8080/api/system
    Content-Type=application/x-www-form-urlencoded
    methods=["GET"]
    :return:
        {'status': 400, 'msg': "不是开发者模式禁止备份数据库"}
        {'status': 200, "msg": "开发者模式系统数据备份成功"}
     ---
    tags:
      - 后端开发者使用->ERROR
    """
    if not config.DEVELOP:
        return jsonify({'status': 400, 'msg': "不是开发者模式禁止备份数据库"})

    ft_ids: list = []
    fts: List[Ft] = g.session.query(Ft).order_by(Ft.id).all()
    for _, itr in enumerate(fts):
        if itr.uuid4 is not None:
            ft_ids.append(itr.id)

    # init_ft_ids: list = [1111, 2222]
    # init_ft_data: list = [
    #     # ##########################################################
    #     {
    #         "address": "DM9100",
    #         "types": "Float",
    #         "describe": "测试:温度上下限",
    #     },
    #     {
    #         "address": "DM9102",
    #         "types": "Short",
    #         "describe": "测试:湿度"
    #     }
    # ]
    # for index, ft_id in enumerate(init_ft_ids):
    #     if ft_id in ft_ids:
    #         for init_data in init_ft_data:
    #             db_data: List[CraftInit] = g.session.query(CraftInit).filter(and_(
    #                                             CraftInit.ft_id == ft_id,
    #                                             CraftInit.address == init_data.get("address")
    #                                         )).first()
    #             if db_data is None:
    #                 g.session.add(CraftInit(
    #                     ft_id=ft_id,
    #                     address=init_data.get("address"),
    #                     types=init_data.get("types"),
    #                     describe=init_data.get("describe")
    #                 ))
    # g.session.commit()

    db_aircraft_all: List[Aircraft] = g.session.query(Aircraft).order_by(Aircraft.id).all()
    for db_aircraft in db_aircraft_all:
        db_route: Routes = g.session.query(Routes).filter(Routes.id == db_aircraft.route_id).first()
        ft_ids_new = []
        route_new = json.loads(db_route.route)
        routes_new = route_new.get("data")
        for itr1 in routes_new:
            second_rts: list = itr1.get("ft_ids")
            for itr2 in second_rts:
                ft_ids_new.append(itr2)
        ft_ids_new = list(set(ft_ids_new))

        for ft_id in ft_ids_new:
            db_craft_init_all: List[CraftInit] = g.session.query(CraftInit).filter(
                CraftInit.ft_id == ft_id
            ).order_by(CraftInit.id).all()

            db_craft_all: List[Craft] = g.session.query(Craft).filter(
                Craft.facility_id == ft_id,
                Craft.aircraft_id == db_aircraft.id,
            ).order_by(Craft.id).all()
            for db_craft_init in db_craft_init_all:
                insert: bool = False

                for db_craft in db_craft_all:
                    if db_craft.address == db_craft_init.address:
                        insert = True
                        break
                if insert is False:
                    g.session.add(Craft(
                        facility_id=ft_id,
                        aircraft_id=db_aircraft.id,
                        address=db_craft_init.address,
                        types=db_craft_init.types,
                        describe=db_craft_init.describe,
                        write=None
                    ))
    g.session.commit()
    return jsonify({'status': 200, 'msg': "开发者模式系统数据备份成功"})
